﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;
using System.Web.Security;

namespace WebAppMatrix.Security
{
    [Serializable]
    public class MatrixPrincipal : IPrincipal
    {
        #region IPrincipal 成员

        private IIdentity _identity;

        /// <summary>
        /// 得到当前主体的身份
        /// </summary>
        public IIdentity Identity
        {
            get { return _identity; }
        }

        /// <summary>
        /// 确定当前主体是否属于某一个角色
        /// </summary>
        /// <param name="roleName">角色名</param>
        /// <returns>如果属于则返回true，否则为false</returns>
        public bool IsInRole(string roleName)
        {
            if (Identity == null || !Identity.IsAuthenticated || string.IsNullOrEmpty(Identity.Name))
                return false;

            // 注意：不能用 Security.CurrentUser.IsInRole来判断，因为会引起死循环。
            // 需要通过role provider直接确定
            return Roles.IsUserInRole(Identity.Name, roleName);
        }

        #endregion

        public MatrixPrincipal(IIdentity identity)
        {
            _identity = identity;
        }
    }
}
